/*
** main.c for  in /home/lund/Projets/SysUnixAv/feutrace
** 
** Made by florian dewulf
** Login   <dewulf_f@epitech.net>
** 
** Started on  Sat Jun 22 22:41:01 2013 florian dewulf
** Last update Sun Jun 23 18:36:54 2013 florian dewulf
*/

#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<sys/ptrace.h>
#include	<unistd.h>
#include	"ftrace.h"

static int	exec_cmd(char **av)
{
  int		pid;

  if ((pid = fork()) == -1)
    xerror("fork");
  if (pid == 0)
    {
      if (ptrace(PT_TRACE_ME, pid, NULL, NULL) == -1)
	xerror("ptrace");
      execvp(av[0], av);
      xerror("execvp");
    }
  return (pid);
}

static int	usage()
{
  printf("Usage :\n");
  printf("./ftrace executable + args\n");
  printf("./ftrace -p PID\n");
  return (0);
}

int		main(int ac, char **av)
{
  pid_t		pid;
  char		*filename;

  if (ac <= 1 || (ac > 1 && strcmp(av[1], "-p") == 0 && ac != 3))
    return (usage());
  if (strcmp(av[1], "-p") == 0)
    {
      filename = NULL;
      pid = atoi(av[2]);
      ptrace(PTRACE_ATTACH, pid, NULL, NULL);
    }
  else
    {
      filename = av[1];
      pid = exec_cmd(&(av[1]));
    }
  ftrace(pid, filename);
  return (0);
}
